package org.mozhu.mboot.core.template.freemarker;

import com.google.common.collect.Maps;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.mozhu.mboot.core.template.TemplateRender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

public class FreemarkerTemplateRender implements TemplateRender {

	private static final Logger LOGGER = LoggerFactory.getLogger(FreemarkerTemplateRender.class);

	private Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
	private StringTemplateLoader stringLoader = new StringTemplateLoader();
	private Map<String, Template> templates = Maps.newHashMap();

	public FreemarkerTemplateRender() {
		cfg.setTemplateLoader(stringLoader);
		cfg.setClassicCompatible(true);
	}

	@Override
	public String render(String templateContent, Map<String, Object> model) {
		Template template = getTemplate(templateContent);
		try {
			StringWriter writer = new StringWriter();
			template.process(model, writer);
			return writer.toString();
		} catch (Exception e) {
			LOGGER.error("Render template failed!", e);
			throw new IllegalStateException("Render template failed!", e);
		}
	}

	private Template getTemplate(String templateContent) {
		if (templates.containsKey(templateContent)) {
			return templates.get(templateContent);
		}
		stringLoader.putTemplate(templateContent, templateContent);
		try {
			Template template = cfg.getTemplate(templateContent);
			templates.put(templateContent, template);
			return template;
		} catch (IOException e) {
			LOGGER.error("Get template failed!", e);
		}
		return null;
	}

}
